package handle

import (
	"server/game/cache"
	"server/game/define/helper"
	"server/game/model"
	"server/share/config"

	"github.com/hwcer/cosgo/times"
	"github.com/hwcer/cosgo/values"
	"github.com/hwcer/logger"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
	"github.com/hwcer/yyds/options"
	"github.com/hwcer/yyds/players"
	"github.com/hwcer/yyds/players/player"
)

type roleBan struct {
	Ban int32 `json:"-" bson:"ban"`
}

func Online(c *context.Context, guid string, uid string) (reply any, err error) {
	if uid == "" {
		return nil, values.Error("uid empty")
	}
	if guid == "" {
		return nil, c.Error("guid empty")
	}
	//查询是否被禁用
	b := &roleBan{}
	if tx := db.Model(&model.Role{}).Select("ban").Where(uid).Find(b); tx.Error != nil {
		return nil, tx.Error
	} else if tx.RowsAffected == 0 {
		return nil, errors.New("uid not exist")
	} else if b.Ban > 0 {
		return nil, errors.ErrRoleIsBan
	}

	err = players.Login(uid, c.Metadata(), func(p *player.Player) error {
		doc := cache.GetRole(p.Updater)
		role := doc.All()
		if guid != role.Guid {
			return values.Error("uid error")
		}
		onlineVerify(p, role)
		if e := onlineEvent(c, p); e != nil {
			return e
		}
		if _, e := p.Submit(); e != nil {
			return e
		}
		c.SetMetadata(options.ServiceMetadataUID, uid)

		//todo 并发问题
		reply = role
		return nil
	})
	return
}

// verify 校验数据
func onlineVerify(p *player.Player, role *model.Role) {
	if role.IncubateList == nil {
		role.IncubateList = model.IncubateList{}
	}
	for _, v := range config.Data.Incubator {
		if v.UnlockBuildLevel == 0 && role.IncubateList[v.ID] == nil {
			role.IncubateList[v.ID] = &model.Incubate{}
		}
	}
	if len(role.HelpUnit) == 0 {
		role.HelpUnit = model.RoleHelpMgr{}
		role.HelpUnit[1] = model.RoleHelp{}
		role.HelpUnit[2] = model.RoleHelp{}
		role.HelpUnit[3] = model.RoleHelp{}
	}

}
func onlineEvent(c *context.Context, p *player.Player) (err error) {
	doc := cache.GetRole(p.Updater)
	doc.Set("update", p.Unix())
	role := doc.Any().(*model.Role)

	//注册第一次登录
	if role.Install == 0 {
		doc.Set("install", int8(1))
		for k, v := range config.Data.Install {
			p.Add(k, v.Val)
		}
	}
	now := times.New(p.Now())
	today := now.Daily(0)
	//每日第一次登录
	last := role.Update
	if role.Update < today.Now().Unix() {
		p.Emit(config.Data.Events.Login, 1)
	}
	//同步数据
	args := helper.SocialUpdateFromRole(role, p.Unix(), last)
	if _, err = c.Async(nil, options.ServiceTypeLocator, "character/online", args); err != nil {
		logger.Alert("同步角色信息时出现错误:%v", err)
	}
	return
}
